package com.qinker.robot.hook.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by Irany 2019/11/6 0:39
 */
public class RobotChatUtils {

    private static final String APP_ID = "2123641430";

    private static final String APP_KEY = "EsW65jAWKTigLSmy";

    public static void main(String[] args) throws Exception {
        System.out.println(getAnswer("你好"));
    }

    public static String getAnswer(String message) throws Exception {
        String responseStr = OkHttpClientUtil.doGet("https://api.ai.qq.com", "/fcgi-bin/nlp/nlp_textchat", null, RobotChatUtils.getSignature(getKeybyvalue(message)));
        JSONObject responseObj = JSON.parseObject(responseStr);

        Integer ret = responseObj.getInteger("ret");
        if (ret == 0) {
            return responseObj.getJSONObject("data").getString("answer");
        }
        return responseObj.getString("msg");
    }

    /**
     * 随机字符串
     *
     * @param length x
     * @return x
     */
    public static String getRandomString(int length) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 参数组合
     */
    public static Map<String, String> getKeybyvalue(String msg) {

        String session = "10000";
        Map<String, String> params = new HashMap<>();
        params.put("app_id", APP_ID);
        params.put("time_stamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("nonce_str", getRandomString(16));
        params.put("session", session);
        params.put("question", msg);

        return params;

    }

    /**
     * SIGN签名生成算法-JAVA版本 通用。默认参数都为UTF-8适用
     *
     * @param params 请求参数集，所有参数必须已转换为字符串类型
     * @return 签名
     * @throws IOException
     */
    public static Map<String, String> getSignature(Map<String, String> params) throws IOException {
        Map<String, String> sortedParams = new TreeMap<>(params);
        Set<Map.Entry<String, String>> entrys = sortedParams.entrySet();
        StringBuilder baseString = new StringBuilder();
        for (Map.Entry<String, String> param : entrys) {
            if (param.getValue() != null && !"".equals(param.getKey().trim()) &&
                    !"sign".equals(param.getKey().trim()) && !"".equals(param.getValue())) {
                baseString.append(param.getKey().trim()).append("=")
                        .append(URLEncoder.encode(param.getValue(), "UTF-8")).append("&");
            }
        }
        if (baseString.length() > 0) {
            baseString.deleteCharAt(baseString.length() - 1).append("&app_key=")
                    .append(APP_KEY);
        }
        try {
            String sign = MD5Utils.getMD5String(baseString.toString());
            sortedParams.put("sign", sign);

        } catch (Exception ex) {
            throw new IOException(ex);
        }
        return sortedParams;
    }

}
